package net;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    Socket socket;

    public TcpEchoClient(String serverIp, int port) throws Exception {
        //对于tcp而言, 它是会先保存对端的信息(ip port)来与对端建立连接
        //而且对于这个socket构造方法来说 不需要将String的ip转成InetAddress
        socket = new Socket(serverIp, port);
    }

    public void start() throws Exception {
        Scanner scanner = new Scanner(System.in);
        System.out.println("开启客户端");
        //通过socket网卡来进行发送请求和接受响应, 所以先获取到对应的流对象,通过这个流对象来转发接受数据
        try (InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream()) {
            while (true) {
                Scanner scanner1 = new Scanner(inputStream);
                PrintWriter writer = new PrintWriter(outputStream);//这里得flush刷新是将缓存发送出去,否则数据一直搁缓冲区内待着
                //1.获取到用户的请求
                System.out.println("请输入发送的请求:");
                String request = scanner.next();
                //2.发送请求
                writer.println(request);
//                writer.print(request);//不能使用print 否则少个\n会导致hasNext方法阻塞
                //需要将刷新一下,将缓冲区的内容发送出去
                writer.flush();
                //3.接受响应
                String response = scanner1.next();
                System.out.println("服务器响应:" + response);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1", 9090);
        client.start();
    }


}
